﻿#region copyright
//<copyright>
// Copyright(C) 2012 TrackerRealm Corporation
// This file is part of the open source project - Jazz. http://jazz.codeplex.com
// 
// Jazz is open software: you can redistribute it and/or modify it 
// under the terms of the GNU Affero General Public License (AGPL) as published by 
// the Free Software Foundation, version 3 of the License.
// 
// Jazz is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty 
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
//  See the GNU Affero General Public License (AGPL) for more details.
// 
// You should have received a copy of the GNU General Public 
// License along with Jazz.  If not, see <http://www.gnu.org/licenses/>.
//
// REMOVAL OF THIS NOTICE IS VIOLATION OF THE COPYRIGHT. 
//</copyright>
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using TrackerRealm.Jazz.Common;
using System.Reflection;

namespace TrackerRealm.Jazz.Client.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class JazzServices
    {

        #region GetTypeFromName(string className)
        /// <summary>
        /// Returns the '<see cref="jObject"/>' type given the class name.
        /// <para>Note: This assumes that the class name is unique across all namespaces.</para>
        /// </summary>
        /// <param name="className">A class name.</param>
        /// <returns></returns>
        public static Type GetTypeFromShortName(string className)
        {
            List<Type> list = new List<Type>();
            Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly a in loadedAssemblies)
            {
                if(a.FullName.StartsWith("mscorlib,"))continue;
                if (a.FullName.StartsWith("System.")) continue;
                if (a.FullName.StartsWith("System,")) continue;
                if (a.FullName.StartsWith("Microsoft.")) continue;
                if (a.FullName.StartsWith("PostSharp,")) continue;

                Type[] types = a.GetTypes().ToArray() ;
                types = types.Where(t => t.Name == className).ToArray();
               
                list.AddRange(a.GetTypes().Where(t => t.Name == className));
            }
            if (list.Count == 0)
                throw new ArgumentException(string.Format("No assembly was found with the name '{0}'.", className), "className");
            if (list.Count > 1)
                throw new ArgumentException(string.Format("Duplicate types found with the name '{0}'.  The name must be unique across Namespaces.", className), "className");
            return list[0];
        }
        #endregion
        /// <summary>
        /// A cache used to increase performance.
        /// </summary>
        static Dictionary<string, Type> typeDict = new Dictionary<string, Type>();
        #region GetTypeFromName(string fullClassName)
        /// <summary>
        /// Returns the '<see cref="jObject"/>' type given the class name.
        /// <para>Note: This assumes that the assembly name is the same as the namespace name.</para>
        /// </summary>
        /// <param name="fullClassName">A 'Full' class name.</param>
        /// <returns></returns>
        public static Type GetTypeFromName(string fullClassName)
        {
            // get namespace from the className
            string ns = GetNamespaceFromFullClassName(fullClassName);
            Type t;
            if (typeDict.TryGetValue(ns + ":" + fullClassName, out t)) return t;
            Assembly assembly = null;
            Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly a in loadedAssemblies)
            {
                if (a.FullName.StartsWith(ns + ","))// the comma (",") insures an acurrate comparison.
                {
                    assembly = a;
                    break;
                }
            }
            if (assembly == null)
                throw new ArgumentException(string.Format("No assembly was found with the name '{0}'.", ns), "fullClassName");
            t = assembly.GetType(fullClassName, throwOnError: true);
            typeDict.Add(ns + ":" + fullClassName, t);
            return t;
        }
        #endregion
        #region GetTypeFromName(string assemblyName, string fullClassName)
        /// <summary>
        /// Returns the '<see cref="jObject"/>' type given the assembly and class name.
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="fullClassName"></param>
        /// <returns></returns>
        public static Type GetTypeFromName(string assemblyName, string fullClassName)
        {
            Type t;
            if (typeDict.TryGetValue(assemblyName + ":" + fullClassName, out t)) return t;
            Assembly assembly = null;
            Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly a in loadedAssemblies)
            {
                if (a.FullName.StartsWith(assemblyName + ",")) // the comma (",") insures an acurrate comparison.
                {
                    assembly = a;
                    break;
                }
            }
            if (assembly == null)
                throw new ArgumentException(string.Format("No assembly was found with the name '{0}'.", assemblyName), "assemblyName");
            t = assembly.GetType(fullClassName, throwOnError: true);
            typeDict.Add(assemblyName + ":" + fullClassName, t);
            return t;
        }
        #endregion
        #region GetNamespaceFromFullClassName
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fullClassName"></param>
        /// <returns></returns>
        public static string GetNamespaceFromFullClassName(string fullClassName)
        {
            string[] classNames = fullClassName.Split('.');
            Array.Resize(ref classNames, classNames.Length - 1);
            string ns = string.Join(".", classNames);
            return ns;
        }
        #endregion
    }

}

